const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

// 获取整张试卷批阅数据
exports.wholePaperBatchReview = async (req, res) => {
  try {
    const { reviewAssignmentId, uniquePaperId } = req.body;
    
    // 参数验证
    if (!reviewAssignmentId) {
      return res.status(400).json({
        code: 400,
        message: '批阅任务ID不能为空',
        success: false
      });
    }

    if (!uniquePaperId) {
      return res.status(400).json({
        code: 400,
        message: '学生试卷ID不能为空',
        success: false
      });
    }

    // 将字符串ID转换为数字
    const assignmentId = parseInt(reviewAssignmentId);
    const paperId = parseInt(uniquePaperId);

    // 首先检查批阅任务是否存在
    const reviewAssignment = await prisma.review_assignment.findUnique({
      where: { id: assignmentId }
    });

    if (!reviewAssignment) {
      return res.status(404).json({
        code: 404,
        message: '批阅任务不存在',
        success: false
      });
    }

    // 获取考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: reviewAssignment.examination_id }
    });

    // 获取考试名称
    const examinationName = examination ? examination.name : '';

    // 获取试卷总分
    let paperFullMark = 0;
    if (examination && examination.exam_plan_id) {
      // 从组卷方案中获取总分
      const examPlanDetails = await prisma.exam_plan_details.findMany({
        where: {
          exam_plan_id: examination.exam_plan_id
        },
        select: {
          score: true
        }
      });
      
      // 计算总分
      paperFullMark = examPlanDetails.reduce((total, detail) => 
        total + (detail.score || 0), 0);
    }

    // 获取该批阅任务关联的所有学生试卷ID（去重）
    const paperDetails = await prisma.review_assignment_detail.findMany({
      where: { 
        review_assignment_id: assignmentId,
        student_paper_id: { not: null } // 确保是按试卷分配的
      },
      select: {
        student_paper_id: true,
        status: true
      }
    });

    // 获取不重复的学生试卷ID
    const uniquePaperIds = [...new Set(paperDetails.map(detail => detail.student_paper_id))];

    // 获取student_paper表中的examination_status信息
    const studentPapersWithStatus = await prisma.student_paper.findMany({
      where: {
        id: {
          in: uniquePaperIds
        }
      },
      select: {
        id: true,
        examination_status: true
      }
    });

    // 创建一个映射表，用于存储每个student_paper_id对应的examination_status
    const statusMap = new Map();
    studentPapersWithStatus.forEach(paper => {
      statusMap.set(paper.id, paper.examination_status || 0);
    });

    // 根据examination_status字段排序uniquePaperIds
    uniquePaperIds.sort((a, b) => {
      const statusA = statusMap.get(a) || 0;
      const statusB = statusMap.get(b) || 0;
      return statusA - statusB;
    });

    // 计算总试卷数
    const total = uniquePaperIds.length;
    
    // 查询已完成批阅的试卷数量
    let doneTotal = 0;
    if (reviewAssignment.assignment_strategy === 1) {
      // 直接从student_paper表中查询examination_status=2（批阅完成）的记录数量
      doneTotal = await prisma.student_paper.count({
        where: {
          id: { in: uniquePaperIds },
          examination_status: 2  // 2表示批阅完成
        }
      });
    } else {
      // 对于非按试卷分配的策略，继续使用原有逻辑
      for (const pid of uniquePaperIds) {
        // 获取该试卷所有批阅详情
        const paperDetailStatuses = await prisma.review_assignment_detail.findMany({
          where: {
            review_assignment_id: assignmentId,
            student_paper_id: pid
          },
          select: {
            status: true
          }
        });
        
        // 如果该试卷的所有批阅详情都已完成（status=1），则计入已完成数量
        if (paperDetailStatuses.length > 0 && paperDetailStatuses.every(detail => detail.status === 1)) {
          doneTotal++;
        }
      }
    }

    // 获取学生试卷信息
    const studentPaper = await prisma.student_paper.findUnique({
      where: { id: paperId }
    });

    if (!studentPaper) {
      return res.status(404).json({
        code: 404,
        message: '学生试卷不存在',
        success: false
      });
    }

    // 获取学生信息
    let student = null;
    if (studentPaper.user_id) {
      student = await prisma.user.findUnique({
        where: { id: studentPaper.user_id }
      });
    }

    // 获取学生班级信息
    let classesName = '';
    if (student) {
      const studentClass = await prisma.student_classes.findFirst({
        where: { student_id: studentPaper.user_id }
      });

      if (studentClass && studentClass.classes_id) {
        const classes = await prisma.classes.findUnique({
          where: { id: studentClass.classes_id }
        });
        classesName = classes ? classes.name : '';
      }
    }

    // 构建学生数据
    const studentData = {
      name: student ? student.name : '',
      account: student ? student.account : '',
      classesName,
      examinationStatus: studentPaper.examination_status,
      totalScore: studentPaper.total_score
    };

    // 获取该学生试卷的所有主观题详情
    // 首先获取主观题的ID列表
    const subjectiveQuestionIds = await prisma.question.findMany({
      where: { answer_type_id: 2 }, // 假设2表示主观题
      select: { id: true }
    }).then(results => results.map(q => q.id));

    // 然后获取该学生试卷的主观题详情
    const paperDetailsData = await prisma.paper_detail.findMany({
      where: {
        student_paper_id: paperId,
        question_id: {
          in: subjectiveQuestionIds
        }
      }
    });

    // 获取每个主观题的详细信息
    const studentPaperDetail = await Promise.all(paperDetailsData.map(async (detail) => {
      // 获取问题信息
      const question = await prisma.question.findUnique({
        where: { id: detail.question_id }
      });

      // 获取主观题答案信息
      let subjectiveAnswer = null;
      if (question && question.answer_id) {
        subjectiveAnswer = await prisma.subjective_answers.findUnique({
          where: { id: question.answer_id }
        });
      }

      // 获取批阅人信息
      let reviewer = null;
      if (detail.user_id) {
        reviewer = await prisma.user.findUnique({
          where: { id: detail.user_id }
        });
      }

      return {
        id: detail.id,
        questionOrder: detail.question_order,
        questionName: question ? question.name : '',
        questionContent: question ? question.question_content : '',
        studentAnswer: detail.student_answer,
        score: detail.score,
        finalScore: detail.final_score,
        checkDetail: detail.check_detail,
        userId: detail.user_id,
        userName: reviewer ? reviewer.name : '',
        status: detail.status,
        referenceAnswer: subjectiveAnswer ? subjectiveAnswer.reference_answer : '',
        gradingRules: subjectiveAnswer && subjectiveAnswer.grading_rules 
                    ? subjectiveAnswer.grading_rules.split('|') 
                    : []
      };
    }));

    // 按照questionOrder升序排列studentPaperDetail
    studentPaperDetail.sort((a, b) => {
      // 处理可能的null或undefined
      const orderA = a.questionOrder === null || a.questionOrder === undefined ? 
                   Number.MAX_SAFE_INTEGER : a.questionOrder;
      const orderB = b.questionOrder === null || b.questionOrder === undefined ? 
                   Number.MAX_SAFE_INTEGER : b.questionOrder;
      return orderA - orderB;
    });

    // 构建返回列表
    const list = [{
      studentData,
      studentPaperDetail
    }];

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        list,
        total,
        doneTotal,
        examinationName,
        paperFullMark
      }
    });
    
  } catch (error) {
    console.error('获取批阅详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取批阅详情失败',
      success: false,
      error: error.message
    });
  }
};

// 保存当前批阅
exports.saveCurrentCheck = async (req, res) => {
  try {
    const { reviewAssignmentId, paperDetailId, finalScore, checkDetail, userId } = req.body;
    
    // 参数验证
    if (!reviewAssignmentId || !paperDetailId) {
      return res.status(400).json({
        code: 400,
        message: '批阅任务ID和试卷详情ID不能为空',
        success: false
      });
    }

    // 将字符串ID转换为数字
    const assignmentId = parseInt(reviewAssignmentId);
    const detailId = parseInt(paperDetailId);
    const teacherId = parseInt(userId);

    // 首先获取paper_detail记录，确认其存在
    const paperDetail = await prisma.paper_detail.findUnique({
      where: { id: detailId }
    });

    if (!paperDetail) {
      return res.status(404).json({
        code: 404,
        message: '试卷详情不存在',
        success: false
      });
    }

    // 获取student_paper_id，用于后续更新学生试卷状态
    const studentPaperId = paperDetail.student_paper_id;

    // 1. 修改paper_detail表中的记录
    await prisma.paper_detail.update({
      where: { id: detailId },
      data: {
        final_score: parseFloat(finalScore),
        check_detail: checkDetail,
        user_id: teacherId,
        check_time: new Date(),
        status: 1 // 已批阅
      }
    });

    // 2. 修改review_assignment_detail表中的记录
    await prisma.review_assignment_detail.updateMany({
      where: {
        review_assignment_id: assignmentId,
        paper_detail_id: detailId
      },
      data: {
        status: 1 // 已完成批阅
      }
    });

    // 3. 检查该批阅任务下的所有批阅详情是否都已完成
    const allDetails = await prisma.review_assignment_detail.findMany({
      where: {
        review_assignment_id: assignmentId
      }
    });

    const allDone = allDetails.length > 0 && allDetails.every(detail => detail.status === 1);

    // 4. 更新review_assignment表的状态
    await prisma.review_assignment.update({
      where: { id: assignmentId },
      data: {
        status: allDone ? 3 : 2 // 如果全部完成则设为3，否则设为2
      }
    });

    // 5. 如果批阅任务属于按试卷分配策略(strategy=1)，则需要更新学生试卷状态
    const reviewAssignment = await prisma.review_assignment.findUnique({
      where: { id: assignmentId }
    });

    if (reviewAssignment && reviewAssignment.assignment_strategy === 1) {
      // 获取该批阅任务下与该学生试卷相关的所有批阅详情
      const paperDetails = await prisma.review_assignment_detail.findMany({
        where: {
          review_assignment_id: assignmentId,
          student_paper_id: studentPaperId
        }
      });
      
      // 检查与该学生试卷相关的所有批阅详情是否都已完成
      const paperAllDone = paperDetails.length > 0 && paperDetails.every(detail => detail.status === 1);
      
      // 更新学生试卷状态
      if (paperAllDone) {
        await prisma.student_paper.update({
          where: { id: studentPaperId },
          data: {
            examination_status: 2 // 批阅完成
          }
        });
      } else {
        await prisma.student_paper.update({
          where: { id: studentPaperId },
          data: {
            examination_status: 1 // 批阅中
          }
        });
      }
    }

    
    
    // 6. 计算并更新学生总分
    if (reviewAssignment) {
      // 获取该学生试卷的所有已批改完成的paper_detail
      const scoredDetails = await prisma.paper_detail.findMany({
        where: {
          student_paper_id: studentPaperId,
          status: 1,
          final_score: { not: null }
        },
        select: {
          final_score: true
        }
      });
      
      // 计算总分
      const totalScore = scoredDetails.reduce((sum, detail) => sum + (detail.final_score || 0), 0);
      
      // 更新学生试卷总分
      await prisma.student_paper.update({
        where: { id: studentPaperId },
        data: {
          total_score: totalScore
        }
      });
    }

    return res.status(200).json({
      code: 200,
      message: '批阅保存成功',
      success: true,
      data: null
    });
    
  } catch (error) {
    console.error('保存批阅详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: '保存批阅详情失败',
      success: false,
      error: error.message
    });
  }
};

// 获取单道大题批阅数据
exports.singleQuestionReview = async (req, res) => {
  try {
    const { reviewAssignmentId, reviewAssignmentDetailIds } = req.body;
    
    // 参数验证
    if (!reviewAssignmentId) {
      return res.status(400).json({
        code: 400,
        message: '批阅任务ID不能为空',
        success: false
      });
    }

    if (!reviewAssignmentDetailIds || !Array.isArray(reviewAssignmentDetailIds) || reviewAssignmentDetailIds.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '批阅详情ID数组不能为空',
        success: false
      });
    }

    // 将字符串ID转换为数字
    const assignmentId = parseInt(reviewAssignmentId);
    const detailIds = reviewAssignmentDetailIds.map(id => parseInt(id));

    // 首先检查批阅任务是否存在
    const reviewAssignment = await prisma.review_assignment.findUnique({
      where: { id: assignmentId }
    });

    if (!reviewAssignment) {
      return res.status(404).json({
        code: 404,
        message: '批阅任务不存在',
        success: false
      });
    }

    // 确认是按单道大题分配的批阅任务
    if (reviewAssignment.assignment_strategy !== 2) {
      return res.status(400).json({
        code: 400,
        message: '该批阅任务不是按单道大题分配的',
        success: false
      });
    }

    // 获取考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: reviewAssignment.examination_id }
    });

    // 获取考试名称
    const examinationName = examination ? examination.name : '';

    // 获取该批阅任务下所有批阅详情的数量
    const total = await prisma.review_assignment_detail.count({
      where: { 
        review_assignment_id: assignmentId,
        paper_detail_id: { not: null }
      }
    });
    
    // 获取已完成批阅的批阅详情数量
    const doneTotal = await prisma.review_assignment_detail.count({
      where: { 
        review_assignment_id: assignmentId,
        paper_detail_id: { not: null },
        status: 1
      }
    });

    // 获取指定批阅详情ID的数据
    const reviewDetails = await prisma.review_assignment_detail.findMany({
      where: {
        id: { in: detailIds }
      }
    });

    // 获取每个批阅详情的完整信息
    const list = await Promise.all(reviewDetails.map(async (detail) => {
      // 如果没有关联到paper_detail_id，则跳过
      if (!detail.paper_detail_id) return null;

      // 获取试卷详情信息
      const paperDetail = await prisma.paper_detail.findUnique({
        where: { id: detail.paper_detail_id }
      });
      
      if (!paperDetail) return null;

      // 获取学生试卷信息
      const studentPaper = await prisma.student_paper.findUnique({
        where: { id: paperDetail.student_paper_id }
      });

      if (!studentPaper) return null;

      // 获取题目信息
      const question = await prisma.question.findUnique({
        where: { id: paperDetail.question_id }
      });

      // 获取主观题答案信息
      let subjectiveAnswer = null;
      if (question && question.answer_id) {
        subjectiveAnswer = await prisma.subjective_answers.findUnique({
          where: { id: question.answer_id }
        });
      }

      // 获取批阅人信息
      let reviewer = null;
      if (paperDetail.user_id) {
        reviewer = await prisma.user.findUnique({
          where: { id: paperDetail.user_id }
        });
      }

      return {
        reviewAssignmentDetailId: detail.id,
        paperDetailId: paperDetail.id,
        studentPaperId: paperDetail.student_paper_id,
        questionOrder: paperDetail.question_order,
        questionName: question ? question.name : '',
        questionContent: question ? question.question_content : '',
        studentAnswer: paperDetail.student_answer,
        score: paperDetail.score,
        finalScore: paperDetail.final_score,
        checkDetail: paperDetail.check_detail,
        userId: paperDetail.user_id,
        userName: reviewer ? reviewer.name : '',
        status: paperDetail.status,
        referenceAnswer: subjectiveAnswer ? subjectiveAnswer.reference_answer : '',
        gradingRules: subjectiveAnswer && subjectiveAnswer.grading_rules 
                    ? subjectiveAnswer.grading_rules.split('|') 
                    : []
      };
    }));

    // 过滤掉null值
    const validList = list.filter(item => item !== null);

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        list: validList,
        total,
        doneTotal,
        examinationName
      }
    });
    
  } catch (error) {
    console.error('获取批阅详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取批阅详情失败',
      success: false,
      error: error.message
    });
  }
};
